package com.wuxianedu.volley;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

/**
 * Created by TED on 2016/10/3.
 */
public class MyVolley {
    private static MyVolley mInstance;
    private final RequestQueue mQueue;
    Context mContext;
    private final ImageLoader mLoader;


    private MyVolley(Context context){
        mContext = context;
        mQueue = getRequestQueue();

        mLoader = new ImageLoader(mQueue, new ImageLoader.ImageCache() {
            LruCache<String,Bitmap> cache = new LruCache<>(20);

            @Override
            public Bitmap getBitmap(String url) {
                return  cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url,bitmap);
            }
        });
    }

    /**
     * 达到请求队列
     * @return
     */
    public RequestQueue getRequestQueue() {
        if (mQueue == null){
            return Volley.newRequestQueue(mContext.getApplicationContext());
        }
        return mQueue;
    }

    public static MyVolley getInstance(Context context){
        if (mInstance == null){
            return new MyVolley(context);
        }
        return mInstance;
    }

    /**
     * 用于添加请求到队列中
     * @param request
     * @param <T>
     */
    public <T> void addToQueue(Request<T> request){
        getRequestQueue().add(request);
    }

    /**
     * 用于返回图片加载对象
     * @return
     */
    public ImageLoader getImageLoader(){
        return mLoader;
    }
}
